package com.example.multithread.communication;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * @ClassName CountDownLatch
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/5/14 2:06 PM
 * @Version 1.0
 */
@Slf4j
public class CountDownLatchDemo {

	public static void main(String[] args) throws InterruptedException {
		log.info("来了十个人, 开始选择英雄.");
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		CountDownLatch countDownLatch = new CountDownLatch(10);
		StopWatch stopWatch = new StopWatch();
		stopWatch.start("加载游戏用时详情");
		ReentrantLock reentrantLock = new ReentrantLock();
		log.info("都选好了, 确认. 开始加载游戏, 请做好战斗准备.");
		//开始加载
		IntStream.rangeClosed(1, 10).forEach(i-> executorService.execute(()->{
//			reentrantLock.lock();
			if (i == 3) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			log.info("{}号线程加载完了, 还有{}个玩家没有加载完, 我的电脑排名第{}.", i, countDownLatch.getCount(), 10 - countDownLatch.getCount());
			countDownLatch.countDown();
//			reentrantLock.unlock();
		}));
		countDownLatch.await();
		stopWatch.stop();
		log.info("可以了, 都加载完了.开始战斗");
		log.info(stopWatch.prettyPrint());
	}
}
